package com.zhang.common.exception;

import com.zhang.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//全局捕获异常
@Slf4j
@RestControllerAdvice   //表明从Controller层面捕获异常
public class GlobalExceptionHandler {

    //Shiro异常
    //@ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = ShiroException.class)
    public Result handle(ShiroException e){
        log.error("Shiro异常------------{}", e);
        return Result.setResult(401,"您还没有登录",null);
    }

    //@validation实体类校验异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handle(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        ObjectError error = bindingResult.getAllErrors().stream().findFirst().get();
        log.error("实体类校验异常------------{}", e);
        return Result.fail(error.getDefaultMessage());
    }

    //运行时异常
    @ExceptionHandler(value = RuntimeException.class)
    public Result handle(RuntimeException e){
        log.error("运行时异常------------{}", e);
        return Result.fail(e.getMessage());
    }


    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handle(IllegalArgumentException e){
        log.error("Assert异常------------{}", e);
        return Result.fail(e.getMessage());
    }
}
